/*
 * 创建日期 2004-6-8
 *
 * 更改所生成文件模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
package com.ctsi.commons.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Comparator;

/**
 * @author yueming
 * 排序类，该排序方法是对list中的对象进行排序，如person、organize对象，attrib是要根据对象中的什么字段进行
 * 排序，如person对象中的name排序，则attrib=name；对中文也能按照字母表进行排序.
 * 更改所生成类型注释的模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
public class BeanComparator implements Comparator<Object> {
	private static final Logger  log = LoggerFactory.getLogger(BeanComparator.class);

	private final String attribute1;
	private final String methodName;
	private final String attribute2;
	

 
	public BeanComparator(String attrib1, String attrib2) {
		this.attribute1 = attrib1;
		this.attribute2 = attrib2;
		this.methodName = null;
	}
	public BeanComparator(String methosName ) {
		this.methodName = methosName;
		this.attribute1 = null;
		this.attribute2 = null;
	}
	public int compare(Object o1, Object o2) {
		if (o1 == null) {
			return 1;
		} else if (o2 == null) {
			return -1;
		}
		 int value;
		try {
			Object ret1, ret2;
			if (attribute1!=null){
				ret1 = UtilObject.getBeanValue(o1, this.attribute1);
				ret2 = UtilObject.getBeanValue(o2, this.attribute1);				
			}else{
				ret1 = UtilObject.runMethod(o1, methodName, null);
				ret2 = UtilObject.runMethod(o2, methodName, null);					
			}


			
			value = compareObj(ret1, ret2);
			

			
			if (value == 0 && attribute2 != null) {
				ret1 = UtilObject.getBeanValue(o1, this.attribute2);
				ret2 = UtilObject.getBeanValue(o2, this.attribute2);
				value = compareObj(ret1, ret2);

			}
			return value;

		} catch (Exception e) {
			log.error("compare error return 0",e);
			return 0;
		}
	}
	
    public int compareObj(Object obj1, Object obj2) {
        return ((Comparable)obj1).compareTo(obj2);
    }

}
